package org.lc.oauth.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.parameters.RequestBody;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import org.lc.oauth.dto.RegisteredClientDto;
import org.lc.oauth.service.Oauth2Service;
import org.lc.oauth.vo.LcUserDetails;
import org.lc.oauth.vo.UserVo;
import org.lc.platform.base.result.Result;
import org.lc.platform.boot.annotation.SaveLog;
import org.lc.platform.redis.service.CacheService;
import org.lc.service.system.client.feign.IMenuFeign;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/oauth2")
@Tag(name = "授权模块")
public class OAuth2Controller {
    @Resource
    Oauth2Service oauth2Service;
    @Resource
    IMenuFeign menuFeign;

    @Resource
    CacheService cacheService;

    @Value("${properties.common.init-system.default-role:''}")
    private String defaultRole;

    @GetMapping("/getUserInfo")
    @Operation(summary = "获取当前用户信息")
    public Result<UserVo> getUserInfo(@AuthenticationPrincipal LcUserDetails user) {
        var userInfo = BeanUtil.copyProperties(user, UserVo.class);
        var result = menuFeign.queryMenuListByClientId(user.getClientId());
        if (!ObjUtil.isNull(result) && result.isSuccess() && !ObjUtil.isNull(result.getData())) {
            userInfo.setMenus(result.getData());
        }
        var key = user.getUserId() + ":acls";
        var acls = cacheService.getList(key);
        if (ObjUtil.isNull(acls)) {
            acls = new ArrayList<>();
        }
        userInfo.setAcls(acls);
        if (userInfo.getRoles().contains(defaultRole)) {
            userInfo.setSuperAdmin(true);
        }
        return Result.data(userInfo);
    }

    @PostMapping("/registered/client")
    @Operation(summary = "注册客户端")
    public Result<String> registeredClient(@Valid @RequestBody RegisteredClientDto client) {
        return oauth2Service.registeredClient(client);
    }

    @GetMapping("/getSecret/{clientId}")
    @Operation(summary = "获取客户端得密钥")
    public Result<String> getClientSecret(@PathVariable(name = "clientId") String client) {
        return oauth2Service.getClientSecret(client);
    }

    @GetMapping("/logout")
    @Operation(summary = "退出当前登录(主动)")
    public Result<Boolean> logout(@AuthenticationPrincipal LcUserDetails user) {
        return Result.data(oauth2Service.logout(ObjUtil.isNull(user) ? null : user.getUserId()));
    }

    @GetMapping("/out-logout")
    @Operation(summary = "退出当前登录（被动）")
    public Result<Boolean> outLogout(@RequestParam("id") String id) {
        return Result.data(oauth2Service.logout(id));
    }
}